<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader :buttons="[]">
            <template #refreshAppend>
                <el-button class="table-header-operate" type="primary" @click="(infoShow = true), (currentRow = {})"
                    ><Icon name="fa fa-plus" class="mr-2" />添加商品</el-button
                >&nbsp;&nbsp;
                <!-- <el-select v-model="filterParams.category" class="ml-3 w-40" clearable
                    ><el-option v-for="item in categoryList" :value="item.id" :key="item.id" :label="item.name"></el-option
                ></el-select> -->
                <el-cascader v-model="filterParams.category" :options="categoryList" :props="{ value: 'id', label: 'name', children: 'children' }" />
                <el-input v-model="filterParams.ean" class="ml-3 w-40" placeholder="完整编号" clearable></el-input>
                <el-input v-model="filterParams.title" class="ml-3 w-40" placeholder="商品名称" clearable></el-input>

                <el-button class="ml-3" @click="handleSearch('reset')"
                    ><Icon name="fa fa-refresh" class="text-current text-sm mr-1"></Icon>重置</el-button
                >
                <el-button type="primary" @click="handleSearch('search')"
                    ><Icon name="fa fa-search" class="text-white text-sm mr-1"></Icon>查询</el-button
                >
            </template>
        </TableHeader>
        <div class="bg-white mt-2 p-3">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
                <el-tab-pane :label="`上架中(${tabNums.onShelfTotal})`" name="first"></el-tab-pane>
                <el-tab-pane :label="`已下架(${tabNums.offShelfTotal})`" name="second"></el-tab-pane>
                <el-tab-pane :label="`已售罄`" name="third"></el-tab-pane>
            </el-tabs>
            <!-- 表格 -->
            <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
            <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
            <Table ref="tableRef">
                <template #thumb>
                    <el-table-column prop="thumb" label="图片" width="110" :align="'center'">
                        <template #default="scope">
                            <div style="height: 100px">
                            <el-image
                                style="width: 70px; height: 100px"
                                preview-teleported
                                :zoom-rate="1.2"
                                :max-scale="7"
                                :min-scale="0.2"
                                :src="scope.row.thumb"
                                :preview-src-list="[scope.row.thumb]"
                                hide-on-click-modal
                            />
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template #title>
                    <el-table-column prop="title" label="商品名称" :align="'left'" style="position: relative">
                        <template #default="scope">
                            <div class="flex">
                                <div class="grow">
                                    <div class="line-clamp-2">{{ scope.row.title }}</div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </template>
                <template #status>
                    <el-table-column prop="title" label="上架状态" width="100" :align="'center'">
                        <template #default="scope">
                            <el-switch
                                v-model="scope.row.status"
                                :active-value="1"
                                :inactive-value="0"
                                @change="changeStatus($event, scope.row)"
                                :disabled="scope.row.stock === 0"
                            ></el-switch>
                        </template>
                    </el-table-column>
                </template>

                <template #listWeight>
                    <el-table-column label="排序" :align="'center'" width="100">
                        <template #default="scope">
                            <div class="group transition ease-in-out">
                                {{ scope.row.list_weight }}
                            </div></template
                        >
                    </el-table-column>
                </template>
                <template #stock>
                    <el-table-column label="SKU库存" :align="'center'">
                        <template #default="scope">
                            <el-popover placement="left" :width="400" trigger="click">
                                <template #reference>
                                    <el-button size="small">库存: {{ scope.row.stock }}件</el-button>
                                </template>
                                <el-table :data="scope.row.skus" height="200px" size="small" stripe>
                                    <el-table-column property="date" label="商品规格" :align="'center'">
                                        <template #default="{ row }">
                                            <div class="flex flex-wrap gap-2 justify-center">
                                                <el-tag v-for="(item, index) in row.productSpec" :key="index">{{ item }}</el-tag>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column property="name" label="图片" :align="'center'" width="100">
                                        <template #default="{ row }">
                                            <div class="flex justify-center">
                                                <el-image
                                                    :src="row.thumb"
                                                    style="width: 40px; height: 40px"
                                                    class="rounded border-solid border border-slate-200"
                                                    fit="cover"
                                                    :preview-src-list="[row.thumb]"
                                                    preview-teleported
                                                    hide-on-click-modal
                                                ></el-image>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="stock" label="库存(件)" :align="'center'" width="100" />
                                </el-table>
                            </el-popover>
                        </template>
                    </el-table-column>
                </template>
                <template #operate>
                    <el-table-column label="操作" :align="'center'">
                        <template #default="scope">
                            <div class="flex justify-center">
                                <el-tooltip class="box-item" effect="dark" content="编辑" placement="top">
                                    <el-button type="primary" size="small" @click="(infoShow = true), (currentRow = scope.row)" class="ml-3 w-7 h-7">
                                        <Icon name="fa fa-pencil" class="text-white text-lg"></Icon>
                                    </el-button>
                                </el-tooltip>
                                <el-popconfirm
                                    width="220"
                                    confirm-button-text="删除"
                                    cancel-button-text="取消"
                                    title="确定删除选中记录?"
                                    @confirm="handleDelete(scope.row)"
                                    confirm-button-type="danger"
                                >
                                    <template #reference>
                                        <div>
                                            <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                                                <el-button type="danger" size="small" class="ml-3 w-7 h-7">
                                                    <Icon name="fa fa-trash" class="text-white text-lg"></Icon>
                                                </el-button>
                                            </el-tooltip>
                                        </div>
                                    </template>
                                </el-popconfirm>
                            </div>
                        </template>
                    </el-table-column>
                </template>
            </Table>
        </div>

        <!-- 表单 -->
        <FastEditInfo
            :modelValue="fastEditShow"
            :categoryList="categoryList"
            @close="(value: any) => (fastEditShow = value)"
            @update="handleClick()"
            :data="currentRow"
        ></FastEditInfo>
        <ProductInfo
            :modelValue="infoShow"
            @close="(value: any) => (infoShow = value)"
            :categoryList="categoryList"
            @update="handleClick()"
            :data="currentRow"
        ></ProductInfo>
        <el-dialog v-model="platformShow" title="选择平台" width="800" destroy-on-close>
            <el-button
                v-blur
                :type="currentPlatformIndex === index ? 'primary' : 'info'"
                plain
                v-for="(item, index) in platformList"
                :key="item.id"
                @click="selectPlatform(item.id, index)"
                >{{ item.name }}</el-button
            >
            <div class="mb-3 mt-6" v-if="select_list && select_list.length > 0">
                同步的商品：
                <el-tag class="ml-3 mb-2" v-for="item in select_list" :key="item.id">{{ item.title }}</el-tag>
            </div>
            <div v-if="select_list && select_list.length > 0" class="flex items-center h-10">
                <el-tag type="danger"
                    ><Icon name="fa fa-info-circle" class="text-base mr-1 text-red-500"></Icon>批量同步只能选择当前页商品，翻页无效</el-tag
                >
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="platformShow = false">取消</el-button>
                    <el-button type="primary" @click="synchronization()"> 确认同步 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { baTableApi } from '/@/api/common'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import createAxios from '/@/utils/axios'
import { inputNumber } from '/@/utils/tools'
import { ElMessage } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import FastEditInfo from './FastEditInfo.vue'
import ProductInfo from './ProductInfo.vue'

defineOptions({
    name: 'wms/products',
})

const { t } = useI18n()
const tableRef = ref()
let activeName: any = ref('first') //tab切换绑定值
let sortInput: any = ref(null) // 排序输入框
let sortInputRef: any = ref(null) // 排序框实例
let tabNums = ref({
    onShelfTotal: 0,
    offShelfTotal: 0,
    soldOutTotal: 0,
}) //上架中,已下架,已售罄数量
let filterParams: any = ref({
    status: 1, // 0为未上架  1为上架中
    scock: null, // 1=已售罄
    category: null, // 分类ID
    ean: null, //编号
    money_price_min: null, // 起始金额
    money_price_max: null, // 结束金额
    title: null, // 标题
    order_by: null, // 1=商品金额降序 2=商品金额升序 3=创建时间降序 4= 创建时间升序
    brand_id: null, //品牌ID
})
let categoryList: any = ref([]) // 类别列表
let fastEditShow: any = ref(false) // 控制快速修改信息的弹层
let currentRow: any = ref({}) // 当前选择的行数据
let infoShow: any = ref(false) // 控制修改信息的弹层
let platformShow: any = ref(false) //控制选择平台的弹窗
let platformList: any = ref([]) //平台列表
let currentPlatformIndex: any = ref(0) //选择的平台索引
let platform_id: any = ref() //选择的平台id
let select_list: any = ref([]) //批量选择的数组
let select_id_list: any = ref([]) //批量选择的id数组

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(new baTableApi('/admin/wms.Products/'), {
    pk: 'id',
    filter: {
        status: 1,
    },
    column: [
        // { type: 'selection', align: 'center', operator: false },
        {
            label: t('wms.products.thumb'),
            prop: 'thumb',
            slotName: 'thumb',
            render: 'slot',
        },
        { label: t('wms.products.number'), prop: 'ean', align: 'center', width: 110 },
        { label: t('wms.products.category_name'), prop: 'category_names', align: 'center', width: 150 },
        { label: t('wms.products.money_price'), prop: 'money_price', align: 'center', width: 150 },
        {
            label: t('wms.products.title'),
            prop: 'title',
            slotName: 'title',
            render: 'slot',
            width: 110,
        },
        { label: t('wms.products.list_weight'), prop: 'listWeight', align: 'center', slotName: 'listWeight', render: 'slot' },
        { label: t('wms.products.sales'), prop: 'sales', align: 'center', slotName: 'sales', render: 'slot' },
        { label: t('wms.products.created_at'), prop: 'created_at', align: 'center', operator: 'eq', width: 160 },
        {
            label: t('wms.products.responsible_person_text'),
            prop: 'admin.username',
            align: 'center',
        },
        { label: t('wms.products.status'), prop: 'status', align: 'center', slotName: 'status', render: 'slot' },
        { label: t('wms.products.stock'), prop: 'stock', align: 'center', slotName: 'stock', render: 'slot' },
        { label: t('Operate'), align: 'center', render: 'slot', slotName: 'operate' },
    ],
    dblClickNotEditColumn: [undefined],
})

provide('baTable', baTable)
let filter = ref(baTable.table.filter)
//切换Tab事件
const handleClick = () => {
    filterParams.value.stock = null
    filterParams.value.status = null
    if (activeName.value === 'first') {
        filterParams.value.status = 1
    } else if (activeName.value === 'second') {
        filterParams.value.status = 0
    } else if (activeName.value === 'third') {
        filterParams.value.stock = 1
    }
    filter.value!.status = filterParams.value.status
    filter.value!.stock = filterParams.value.stock
    baTable.getIndex()?.then(() => {
        tabNums.value = {
            onShelfTotal: baTable.table.allData!.on_shelf_total,
            offShelfTotal: baTable.table.allData!.off_shelf_total,
            soldOutTotal: baTable.table.allData!.sold_out_total,
        }
    })
}

// 快捷上下架
const changeStatus = (val: any, row: any) => {
    baTable.table.loading = true
    createAxios({ url: '/admin/wms.Products/changeStatus', method: 'post', data: { id: row.id, status: val } }).then((res) => {
        if (res.code === 1) {
            ElMessage({ type: 'success', message: res.msg })
            handleClick()
        }
    })
}

// 快捷排序
const changeSort = (val: any, row: any) => {
    baTable.table.loading = true
    createAxios({ url: '/admin/wms.Products/changeSort', method: 'post', data: { id: row.id, list_weight: val } }).then((res) => {
        if (res.code === 1) {
            ElMessage({ type: 'success', message: res.msg })
            handleClick()
        }
    })
}

// 获取类别列表
const getCategoryList = () => {
    createAxios({ url: '/admin/xmwms.Category/index', method: 'get', params: { status: 1 } }).then((res) => {
        if (res.code === 1) {
            categoryList.value = res.data.list
        }
    })
}

//搜索操作
const handleSearch = (type: string) => {
    if (type === 'reset') {
        filterParams.value = {
            status: 1, // 0为未上架  1为上架中
            scock: null, // 1=已售罄
            category1_id: null, // 分类ID
            ean: null, //编号
            money_price_min: null, // 起始金额
            money_price_max: null, // 结束金额
            title: null, // 标题
            order_by: null, // 1=商品金额降序 2=商品金额升序 3=创建时间降序 4= 创建时间升序
            brand_id: null, //品牌ID
        }
    }
    //赋值给baTable的filter对象
    filter.value!.category = filterParams.value.category
    filter.value!.ean = filterParams.value.ean
    filter.value!.money_price_min = filterParams.value.money_price_min
    filter.value!.money_price_max = filterParams.value.money_price_max
    filter.value!.title = filterParams.value.title
    filter.value!.order_by = filterParams.value.order_by
    filter.value!.brand_id = filterParams.value.brand_id
    baTable.getIndex()?.then(() => {
        tabNums.value = {
            onShelfTotal: baTable.table.allData!.on_shelf_total,
            offShelfTotal: baTable.table.allData!.off_shelf_total,
            soldOutTotal: baTable.table.allData!.sold_out_total,
        }
    })
}

// 删除商品
const handleDelete = (row: any) => {
    baTable.table.loading = true
    createAxios({ url: '/admin/wms.Products/del', method: 'DELETE', params: { ids: [row.id] } }).then((res) => {
        if (res.code === 1) {
            ElMessage({ type: 'success', message: res.msg })
            handleClick()
        }
    })
}

// 获取平台列表
const getPlatformList = () => {
    createAxios({ url: '/admin/xmwms.Platform/index', method: 'get' }).then((res) => {
        if (res.code === 1) {
            platformList.value = res.data.list
            platform_id.value = res.data.list[0].id
        }
    })
}

//选择平台
const selectPlatform = (id: any, index: any) => {
    currentPlatformIndex.value = index
    platform_id.value = id
}

//单个同步
const singleSynchronization = (row: any) => {
    platformShow.value = true
    currentRow.value = row
    select_list.value = [row]
    select_id_list.value = [row.id]
}

//批量同步
const batchSynchronization = () => {
    platformShow.value = true
    select_list.value = tableRef.value.getRef().getSelectionRows()

    console.log(select_list.value, 'select_list')
    select_id_list.value = []
    select_list.value?.forEach((item: any) => {
        select_id_list.value.push(item.id)
    })
}

//调用同步接口
const synchronization = () => {
    if (!select_id_list.value || select_id_list.value.length === 0) {
        ElMessage({ type: 'warning', message: '请选择商品' })
        platformShow.value = false
        return
    }
    platformShow.value = false
    let ids = select_id_list.value.join(',')
    createAxios({ url: '/admin/wms.Products/syncProduct', method: 'post', data: { ids: ids, platform: platform_id.value } }).then((res) => {
        if (res.code === 1) {
            ElMessage({ type: 'success', message: '同步成功' })
        } else {
            ElMessage({ type: 'error', message: res.msg })
        }
    })
}

onMounted(() => {
    getCategoryList()
    getPlatformList()
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
        tabNums.value = {
            onShelfTotal: baTable.table.allData!.on_shelf_total,
            offShelfTotal: baTable.table.allData!.off_shelf_total,
            soldOutTotal: baTable.table.allData!.sold_out_total,
        }
    })
})
</script>

<style scoped lang="scss">

</style>
